package cn.itsource.hrm.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.sql.DataSource;
import java.util.Arrays;

@Configuration
@EnableAuthorizationServer
public class MyAuthorizationServerConfigurer extends AuthorizationServerConfigurerAdapter {

    //客户端详情：配置客户端请求的参数 ====================================================================
    @Override
    public void configure(ClientDetailsServiceConfigurer clientDetails) throws Exception {
        clientDetails.withClientDetails(clientService());
    }

    @Autowired
    private DataSource dataSource;

    @Bean
    public ClientDetailsService clientService(){
        JdbcClientDetailsService jdbcService = new JdbcClientDetailsService(dataSource);
        // 客户端详情表 密码的加密方式
        jdbcService.setPasswordEncoder(new BCryptPasswordEncoder());
        return jdbcService;
    }



    //授权服务端点：配置授权码和令牌的管理/存储方式 ======================================================
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                //1.密码授权模式需要
                .authenticationManager(authenticationManager)           //密码的认证管理器
                //2.授权码模式服务
                .authorizationCodeServices(authorizationCodeServices())  // 授权码的存储方式
                //3.配置令牌管理服务
                .tokenServices(tokenServices())                          // token的存储方法，客户端的关系, 有效时间
                //允许post方式请求
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }


    @Autowired
    AuthenticationManager authenticationManager;

    @Bean
    public AuthorizationCodeServices authorizationCodeServices(){
        //授权码的存储
        JdbcAuthorizationCodeServices codeServices = new JdbcAuthorizationCodeServices(dataSource);
        return codeServices;
    }

    @Bean
    public AuthorizationServerTokenServices tokenServices(){
        // 令牌的配置
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        //配客户端详情
        defaultTokenServices.setClientDetailsService(clientService());

        //配令牌的存储方式
        defaultTokenServices.setTokenStore(tokenStore());

        //设置token增强 - 设置token转换器
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter()));
        defaultTokenServices.setTokenEnhancer(tokenEnhancerChain);  //jwtAccessTokenConverter()

        //令牌的有效时间
        defaultTokenServices.setAccessTokenValiditySeconds(3000);


        //令牌的刷新
        defaultTokenServices.setReuseRefreshToken(true);
        defaultTokenServices.setSupportRefreshToken(true);
        defaultTokenServices.setRefreshTokenValiditySeconds(20);

        return defaultTokenServices;

    }

    //设置JWT签名密钥。它可以是简单的MAC密钥，也可以是RSA密钥
    private final String sign_key  = "123";

    //JWT令牌校验工具
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter jwtAccessTokenConverter =
                new JwtAccessTokenConverter();
        //设置JWT签名密钥。它可以是简单的MAC密钥，也可以是RSA密钥
        jwtAccessTokenConverter.setSigningKey(sign_key);
        return jwtAccessTokenConverter;
    }

    @Bean
    public TokenStore tokenStore(){

        // return new InMemoryTokenStore(); 存在内存种的
        // 提供JWM的token转换器
        return new JwtTokenStore(jwtAccessTokenConverter());
    }



    // 服务端的安全 ，哪些路径要放行 ===============================
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                //对应/oauth/check_token ，路径放行
                .checkTokenAccess("permitAll()")
                //允许客户端进行表单身份验证,使用表单认证申请令牌
                .allowFormAuthenticationForClients();
    }
}
